package com.my.study.loader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author: yidujun
 * @create: 2022/01/15 14:18
 */
public class DeClassLoader extends ClassLoader {

    private String mLibPath;

    public DeClassLoader(String mLibPath) {
        this.mLibPath = mLibPath;
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String fileName = getFileName(name);
        File file = new File(mLibPath, fileName);

        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int len = 0;
            byte b = 0;
            while ((len = fis.read()) != -1) {
                b = (byte) (len ^ 2);
                bos.write(b);
            }
            byte[] data = bos.toByteArray();

            return defineClass(name, data, 0, data.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.findClass(name);
    }

    /**
     * 获取要加载的文件名
     *
     * @param path 路径
     * @return 文件名
     */
    private String getFileName(String path) {
        int i = path.lastIndexOf(".");
        if (i == -1) {
            return path + ".classen";
        } else {
            return path.substring(i + 1) + ".classen";
        }

    }
}
